package com.ytxg.health_management.dict.controller;

import com.ytxg.health_management.controller.UserController;
import com.ytxg.health_management.dict.pojo.Dict;
import com.ytxg.health_management.dict.service.NewDictService;
import com.ytxg.health_management.pojo.dto.UserDto;
import com.ytxg.health_management.pojo.entity.Result;
import com.ytxg.health_management.util.Const;
import com.ytxg.health_management.util.MyException;
import com.ytxg.health_management.util.ResultCode;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dict")
public class NewDictController {
    // 定义一个日志对象
    private static final Logger log = LoggerFactory.getLogger(NewDictController.class);
    // 注入DictService
    @Resource
    NewDictService dictService;
    // 注入UserController
    @Resource
    UserController userController;

    // 添加字典
    @PostMapping("/add")
    public Result<Integer> addDict(@RequestBody Dict dict, @RequestHeader("Authorization") String token) {
        // 验证token
        Result<UserDto> userDtoResult = userController.tokenAuth(token);

        // 调用DictService的addDict方法添加字典
        dictService.addDict(dict);
        // 记录日志
        log.info("{}新建了一个字典:{}", userDtoResult.getData().getUserName(), dict);
        // 返回成功结果
        return Result.success(Const.SUCCESS, null);
    }


    // 获取字典
    @PostMapping("/getAllDicts")
    public Result<List<Dict>> getAllDicts(@RequestBody Dict dict) {

        List<Dict> dicts = dictService.getDicts(dict);
        // 返回成功结果
        return Result.success(dicts);
    }

    /**
     * 删除字典
     */
    @PostMapping("/deleteDict")
    public Result<String> deleteDict(@RequestBody Dict dict,@RequestHeader("Authorization") String token) {
        Result<UserDto> userDtoResult = userController.tokenAuth(token);
        if(userDtoResult.getData().getLevel()!=Const.ROLE_ADMIN){
            throw new MyException(ResultCode.USER_LEVEL_NOT_MATCH,Const.USER_LEVEL_NOT_MATCH);
        }
        dictService.deleteDict(dict);
        // 返回成功结果
        return Result.success(Const.SUCCESS);
    }

    /**
     * 更新字典
     */
    @PostMapping("/updateDict")
    public Result<String> updateDict(@RequestBody Dict dict,@RequestHeader("Authorization") String token) {
        Result<UserDto> userDtoResult = userController.tokenAuth(token);
        dictService.updateDict(dict);
        return Result.success(Const.SUCCESS);
    }
}